package v1

import (
	"pq/models"
	"github.com/astaxie/beego/orm"
	"github.com/astaxie/beego"
	//"strings"
	"pq/helper"
)

type CsTestLibItemAnswerController struct{
	TokenCheckController
}

func (cac *CsTestLibItemAnswerController) Post(){
	row := new (models.PqTestItemAnswer)
	id,_ := cac.GetInt("id",0)
	row.Body = cac.GetString("body")
	row.PqCsTestItemId,_ = cac.GetInt("pq_cs_test_item_id")
	row.IsRightAnswer,_ = cac.GetInt("is_right_answer")
	master := models.GetMasterDb()
	//slave := models.GetSlaveDb()

	//row.Body = strings.Replace(row.Body,"<img","[img",1)
	row.Body = helper.UploadEditorImageContent(row.Body)
	if(id > 0){
		_,err := master.QueryTable("pq_test_item_answer").Filter("id",id).Update(orm.Params{
			"body" : row.Body,
			"is_right_answer" : row.IsRightAnswer,
		})
		beego.Error(err)
	}else{
		row.Id = 0
		ins, err := master.Insert(row)
		if err != nil {
			beego.Warning(err)
		}
		id = int(ins)
	}
	item := new (models.PqCsTestItem)
	item.SaveAnwsers(row.PqCsTestItemId)
	res := map[string]interface{}{}
	res["id"] = id
	cac.Single(res)
}

func (cac *CsTestLibItemAnswerController) Del(){
	id := cac.Ctx.Input.Param(":id")
	master := models.GetMasterDb()
	slave := models.GetSlaveDb()
	item := new (models.PqCsTestItem)
	var answer models.PqTestItemAnswer
	slave.QueryTable("pq_test_item_answer").Filter("id",id).One(&answer)
	answer.State = -1
	if _,err := master.Update(&answer);err == nil{
		item.SaveAnwsers(answer.PqCsTestItemId)
	}else{
		cac.Fail("Deleted fail","")
	}
	cac.Success("Deleted Successfully")
}